package initialize

import (
	"example.com/m/v2/middleware"
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"io"
	"os"
)

func getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.TimeKey = "time"
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	encoderConfig.EncodeDuration = zapcore.SecondsDurationEncoder
	encoderConfig.EncodeCaller = zapcore.ShortCallerEncoder
	return zapcore.NewConsoleEncoder(encoderConfig) //设置编码模式
}

func getLogWriter(filename string, maxSize, maxBackup, maxAge int) zapcore.WriteSyncer {
	lumberJackLogger := &lumberjack.Logger{
		Filename:   filename,
		MaxSize:    maxSize,   // 每个日志文件的最大大小（MB）
		MaxBackups: maxBackup, // 保留的旧日志文件的最大数量
		MaxAge:     maxAge,    // 保留的旧日志文件的最大天数
		LocalTime:  true,      // 使用本地时间进行归档
	}

	wc := io.MultiWriter(lumberJackLogger, os.Stdout) //也输出到终端
	return zapcore.AddSync(wc)
}

func InitLogger(cfg *middleware.LogConfig, logger **zap.Logger) (err error) {
	writeSyncer := getLogWriter(cfg.Filename, cfg.MaxSize, cfg.MaxBackups, cfg.MaxAge)
	encoder := getEncoder()
	var l = new(zapcore.Level)
	err = l.UnmarshalText([]byte(cfg.Level))
	if err != nil {
		return
	}

	errorWriteSyncer := getLogWriter("log/error.log", cfg.MaxSize, cfg.MaxBackups, cfg.MaxAge)
	errorLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
		return lvl >= zapcore.ErrorLevel
	})
	errCore := zapcore.NewCore(encoder, errorWriteSyncer, errorLevel)

	core := zapcore.NewCore(encoder, writeSyncer, l)

	cors := zapcore.NewTee(core, errCore)

	*logger = zap.New(cors, zap.AddCaller())
	return
}
